package com.attendance.controller;

import com.attendance.Utils.Converter.ApplyConverter;
import com.attendance.Utils.PaginationUtil;
import com.attendance.model.Apply;
import com.attendance.model.Biz.BizApply;
import com.attendance.model.Form.ApplyForm;
import com.attendance.model.Result.Response;
import com.attendance.model.Result.ResultCode;
import com.attendance.service.IApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by OPTIPLEX on 2016/11/29.
 */

@RestController
@RequestMapping("/apply")
public class ApplyController {

    @Autowired
    private IApplyService applyService;

    @RequestMapping(value = "",method = RequestMethod.GET)
    public Response getAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows,
                           @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "asc") String order,
                           @ModelAttribute ApplyForm applyForm){
        PaginationUtil.preset(page, rows, sort, order);
        Response response = new Response();
        List<BizApply> list = applyService.getAll(applyForm);
        response.putResult(list);
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response add(@ModelAttribute ApplyForm applyForm){
        Response response = new Response();
        try {
            Apply apply = ApplyConverter.convert(applyForm);

            applyService.insertSelective(apply);
        } catch (Exception e) {
            return new Response(ResultCode.APPLY_ADD_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.DELETE)
    public Response delete(@ModelAttribute ApplyForm applyForm){
        Response response = new Response();
        try {
            Apply apply = ApplyConverter.convert(applyForm);
            applyService.deleteById(apply.getId());
        } catch (Exception e) {
            return new Response(ResultCode.APPLY_DELETE_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.PUT)
    public Response update(@ModelAttribute ApplyForm applyForm){
        Response response = new Response();
        try {
            Apply apply = ApplyConverter.convert(applyForm);
            applyService.updateSelectiveById(apply);
        } catch (Exception e) {
            return new Response(ResultCode.APPLY_UPDATE_ERROR);
        }
        return response;
    }
}
